package com.to8to.kitt.zkutils;

import java.util.Collection;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.framework.recipes.leader.Participant;
import org.apache.curator.utils.EnsurePath;

import com.to8to.kitt.esb.ZK;

public class LeaderElection {

	public static LeaderSelector elect(String path, LeaderSelectorListenerAdapter listener, boolean autoRequeue)
	{
		LeaderSelector selector = new LeaderSelector(ZK.ZK_CLIENT, path, listener);
		if(autoRequeue)
			selector.autoRequeue();  // not required, but this is behavior that you will probably expect
		selector.start();
		return selector;
	}
	
	
	
	public static void main(String[] args) throws Exception
	{
		String path = "/test_leader_elect";
	
		EnsurePath ensurePath = new EnsurePath(path);

		ensurePath.ensure(ZK.ZK_CLIENT.getZookeeperClient());		
			
		LeaderSelector selector = elect(path, new LeaderSelectorListenerAdapter(){

			@Override
			public void takeLeadership(CuratorFramework client)
					throws Exception {
				
				while(true)
				{
					System.out.println("I am the leader now! ... ");
					Thread.sleep(3000);
				}
			}
			
		}, false);
		
		while(true)
		{
			Collection<Participant> all = selector.getParticipants();
			
			Participant leader = selector.getLeader();
			
			System.out.println("all: " + all);
			System.out.println("leader: " + leader);
			
			Thread.sleep(3000);
		}
		
	}
}
